import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import { getToken, setDynamicRoutes } from '@/utils/auth'
import { fetchRoutes } from '@/api/router'

// 基础路由（无需权限）
const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    name: 'Layout',
    component: Layout,
    redirect: '/login',
    children: [
      {
        path: "/index",
        name: "Index",
        component: () => import('@/views/index/index.vue'),
      },
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/404/index.vue'),
    meta: { hidden: true }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 动态路由加载状态
let isDynamicRoutesLoaded = false

// 创建路由加载错误组件
const RouteLoadingError = {
  template: '<div>路由加载失败，请刷新页面</div>'
}

// 添加动态路由
const addDynamicRoutes = async () => {
  try {
    // 获取路由数据
    const routes = await fetchRoutes()
    // 清除之前可能存在的动态路由（避免重复添加）
    if (router.hasRoute('Layout')) {
      const layoutRoute = router.getRoutes().find(r => r.name === 'Layout')
      if (layoutRoute) {
        layoutRoute.children = []
      }
    }

    // 递归添加路由
    const addRoutes = (routes: any[], parentName?: string) => {
      routes.forEach(route => {
        // 创建路由记录
        const routeRecord: RouteRecordRaw = {
          path: route.path,
          name: route.name,
          // 添加错误处理的组件加载
          component: () => import(`@/views/${route.component}/index.vue`)
            .catch(error => {
              // console.error(`路由组件加载失败: ${route.name}`, error)
              return RouteLoadingError
            }),
          meta: route.meta || {},
          children: []
        }

        // 如果是嵌套路由且有父路由
        if (parentName) {
          router.addRoute(parentName, routeRecord)
          // console.log(`[路由] 添加嵌套路由: ${parentName} -> ${route.name}`)
        }
        // 如果是顶级路由
        else {
          router.addRoute('Layout', routeRecord)
          // console.log(`[路由] 添加动态路由: ${route.name} -> ${route.path}`)
        }

        // 如果有子路由，递归添加
        if (route.children && route.children.length > 0) {
          addRoutes(route.children, route.name)
        }
      })
    }

    // 开始添加路由
    addRoutes(routes)

    // 添加通配路由（确保在最后）
    router.removeRoute('CatchAll') // 先移除可能存在的通配路由
    router.addRoute({
      path: '/:pathMatch(.*)*',
      name: 'CatchAll',
      redirect: '/404',
      meta: { hidden: true }
    })
    // console.log('[路由] 添加通配路由')

    // 更新状态
    isDynamicRoutesLoaded = true
    setDynamicRoutes(true)
    // console.log("所有路由结构：", router.getRoutes());
    return true
  } catch (error) {
    // console.error('动态路由加载失败:', error)
    // console.log("所有路由结构：", router.getRoutes());
    return false
  }
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = getToken()

  // 未登录状态且访问需要权限的页面
  if (!token && to.path !== '/login') {
    next({ path: '/login', replace: true })
    return
  }

  // 已登录状态访问登录页
  if (token && to.path === '/login') {
    next({ path: '/home', replace: true })
    return
  }

  // 已登录但动态路由未加载
  if (token && !isDynamicRoutesLoaded) {
    try {
      // 标记为正在加载，防止重复加载
      isDynamicRoutesLoaded = true

      // 加载动态路由
      const success = await addDynamicRoutes()

      if (success) {
        // 使用 replace 避免回退问题
        next({ ...to, replace: true })
        return
      } else {
        throw new Error('动态路由加载失败')
      }
    } catch (error) {
      // console.error('路由加载异常:', error)
      isDynamicRoutesLoaded = false // 重置状态
      next('/login')
      return
    }
  }

  // 其他情况直接放行
  next()
})

export default router